package com.emergency.direct.service.impl;

import com.emergency.base.domain.File;
import com.emergency.base.domain.Message;
import com.emergency.base.domain.Scenar;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.direct.dao.FileDao;
import com.emergency.direct.dao.MessageDao;
import com.emergency.direct.dao.ScenarDao;
import com.emergency.direct.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 92924 on 2020/3/16.
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private FileDao fileDao;

    @Autowired
    private ScenarDao scenarDao;

    @Autowired
    private IdWorker idWorker;

    @Override
    public Message getMessageById(Long messageId) {
        Message message=null;
        if(CommonUtils.isNullOrEmpty(messageId)){
         return message;
        }
        message=messageDao.findById(messageId).orElse(null);
        return message;
    }

    @Override
    public String saveOrUpdate(Message message) {
        if(CommonUtils.isNullOrEmpty(message.getId())){
            message.setId(idWorker.nextId());
            message.setArmy(message.getPlanDetail().getArmy());
        }
        messageDao.saveAndFlush(message);
        //保存附件
        if(!CommonUtils.isNullOrEmpty(message.getAttachments())){
            saveAttachments(message);
        }
        //根据想定类型判断，如果是实战，组装消息发送至分队接收器
        sendMessageToThird(message);

        return message.getId().toString();
    }

    private void sendMessageToThird(Message message) {
        Scenar scenar=scenarDao.findById(message.getScenar().getId()).orElse(null);
        if(!CommonUtils.isNullOrEmpty(scenar)&&scenar.getType()==2){
         //实战，发送至第三方接收器

        }
    }

    @Override
    public Page<Message> findList(Map searchMap, int page, int size) {

        Specification<Message> specification = createSpecification(searchMap);
        PageRequest pageRequest =  PageRequest.of(page-1, size);
        return messageDao.findAll(specification, pageRequest);
    }

    private void saveAttachments(Message message) {
        //先删除之前的附件
        fileDao.deleteByAttId(message.getId());

       List<File> attachments=message.getAttachments();
        attachments.forEach(attach->{
            attach.setId(idWorker.nextId());
            attach.setAttr(1);
            attach.setAttId(message.getId());
        });
        fileDao.saveAll(attachments);
    }

    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private Specification<Message> createSpecification(Map searchMap) {

        return new Specification<Message>() {

            @Override
            public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 主题
                if (searchMap.get("subject") != null && !"".equals(searchMap.get("subject"))) {
                    predicateList.add(cb.like(root.get("subject").as(String.class), "%" + (String) searchMap.get("subject") + "%"));
                }
                // 发送方
                if (searchMap.get("sendUser") != null && !"".equals(searchMap.get("sendUser"))) {
                    predicateList.add(cb.like(root.get("sendUser").as(String.class), "%" + (String) searchMap.get("sendUser") + "%"));
                }

                // 接收方
                if (searchMap.get("receiveUser") != null && !"".equals(searchMap.get("receiveUser"))) {
                    predicateList.add(cb.like(root.get("receiveUser").as(String.class), "%" + (String) searchMap.get("receiveUser") + "%"));
                }

                // 类型
                if (searchMap.get("type") != null && !"".equals(searchMap.get("type"))) {
                    predicateList.add(cb.equal(root.get("type").as(Integer.class),(Integer)searchMap.get("type")));
                }

                // status
                if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                    predicateList.add(cb.equal(root.get("status").as(Integer.class),(Integer)searchMap.get("status")));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
